<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑采购订单' : '新增采购订单'"
    width="90%"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="purchase-order-form"
    >
      <!-- 基础信息 -->
      <div class="form-section">
        <h3 class="section-title">基础信息</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单主题" prop="orderSubject">
              <el-input
                v-model="form.orderSubject"
                placeholder="请输入采购订单主题"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购单号" prop="purchaseOrderNumber">
              <el-input
                v-model="form.purchaseOrderNumber"
                placeholder="系统自动生成"
                :disabled="true"
              >
                <template #append>
                  <el-checkbox v-model="form.isSystemNumber">系统编号</el-checkbox>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="关联销售订单" prop="relatedSalesOrder">
              <el-input
                v-model="form.relatedSalesOrder"
                placeholder="请选择销售订单"
                clearable
              >
                <template #append>
                  <el-button icon="Document" />
                </template>
              </el-input>
              <el-checkbox v-model="form.doNotBindSalesOrder">不绑定销售订单</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联请购" prop="relatedPurchaseRequest">
              <el-input
                v-model="form.relatedPurchaseRequest"
                placeholder="请选择请购单号"
                clearable
              >
                <template #append>
                  <el-button icon="Document" />
                </template>
              </el-input>
              <el-checkbox v-model="form.doNotBindPurchaseRequest">不绑定请购单号</el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="采购日期" prop="purchaseDate">
              <el-date-picker
                v-model="form.purchaseDate"
                type="date"
                placeholder="请选择日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商名称" prop="supplierId">
              <el-select
                v-model="form.supplierId"
                placeholder="请选择供应商"
                style="width: 100%"
                clearable
                :loading="loadingOptions"
                :disabled="loadingOptions"
              >
                <el-option
                  v-for="supplier in suppliers"
                  :key="supplier.id"
                  :label="supplier.name"
                  :value="supplier.id"
                />
                <el-option v-if="suppliers.length === 0" disabled label="暂无数据" value="" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input
                v-model="form.contactPhone"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购部门" prop="purchasingDepartmentId">
              <el-select
                v-model="form.purchasingDepartmentId"
                placeholder="请选择采购部门"
                style="width: 100%"
                clearable
                :loading="loadingOptions"
                :disabled="loadingOptions"
              >
                <el-option
                  v-for="dept in departments"
                  :key="dept.id"
                  :label="dept.name"
                  :value="dept.id"
                />
                <el-option v-if="departments.length === 0" disabled label="暂无数据" value="" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="关联项目" prop="relatedProjectId">
              <el-select
                v-model="form.relatedProjectId"
                placeholder="请选择项目名称"
                style="width: 100%"
                clearable
                :loading="loadingOptions"
                :disabled="loadingOptions"
              >
                <el-option
                  v-for="project in projects"
                  :key="project.id"
                  :label="project.name"
                  :value="project.id"
                />
                <el-option v-if="projects.length === 0" disabled label="暂无数据" value="" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交付地址" prop="deliveryAddress">
              <el-input
                v-model="form.deliveryAddress"
                placeholder="请输入交付地址"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="备注" prop="remarks">
              <el-input
                v-model="form.remarks"
                type="textarea"
                :rows="3"
                placeholder="请输入备注"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactPerson">
              <el-input
                v-model="form.contactPerson"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="采购人员" prop="purchaserId">
              <el-select
                v-model="form.purchaserId"
                placeholder="请选择采购人员"
                style="width: 100%"
                clearable
                :loading="loadingOptions"
                :disabled="loadingOptions"
              >
                <el-option
                  v-for="person in persons"
                  :key="person.name"
                  :label="person.name"
                  :value="person.id"
                />
                <el-option v-if="persons.length === 0" disabled label="暂无数据" value="" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="contactMethod">
              <el-input
                v-model="form.contactMethod"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="结算方式" prop="settlementMethod">
              <el-select
                v-model="form.settlementMethod"
                placeholder="请选择结算方式"
                style="width: 100%"
                clearable
              >
                <el-option
                  v-for="method in settlementMethods"
                  :key="method.value"
                  :label="method.label"
                  :value="method.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 物品明细 -->
      <div class="form-section">
        <h3 class="section-title">物品明细</h3>
        <div class="detail-actions">
          <el-button type="primary" @click="addDetailItem" icon="Plus">
            添加
          </el-button>
          <el-button type="danger" @click="removeDetailItems" icon="Delete" :disabled="!hasSelectedDetails">
            移除
          </el-button>
        </div>

        <el-table
          :data="form.details"
          border
          style="width: 100%"
          @selection-change="handleDetailSelectionChange"
        >
          <el-table-column type="selection" width="55" />
                  <el-table-column prop="serialNumber" label="序号" width="60" />
        <el-table-column prop="itemNumber" label="物品编号" width="150">
          <template #default="scope">
            <el-input
              v-model="scope.row.itemNumber"
              placeholder="请输入物品编号"
              clearable
            />
          </template>
        </el-table-column>
        <el-table-column prop="itemName" label="物品名称" min-width="150">
          <template #default="scope">
            <el-input
              v-model="scope.row.itemName"
              placeholder="请输入物品名称"
              clearable
            />
          </template>
        </el-table-column>
        <el-table-column prop="specificationModel" label="规格型号" width="120">
          <template #default="scope">
            <el-input
              v-model="scope.row.specificationModel"
              placeholder="请输入规格型号"
              clearable
            />
          </template>
        </el-table-column>
        <el-table-column prop="unit" label="单位" width="120">
          <template #default="scope">
            <el-select
              v-model="scope.row.unit"
              placeholder="请选择单位"
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="unit in units"
                :key="unit.value"
                :label="unit.label"
                :value="unit.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="brand" label="品牌" width="120">
          <template #default="scope">
            <el-input
              v-model="scope.row.brand"
              placeholder="请输入品牌"
              clearable
            />
          </template>
        </el-table-column>
        <el-table-column prop="purchaseQuantity" label="* 采购数量" width="120">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.purchaseQuantity"
              :min="0.01"
              :precision="2"
              style="width: 100%"
              @change="calculateDetailTotal(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="mainUnitQuantity" label="主单位数量" width="120">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.mainUnitQuantity"
              :min="0"
              :precision="2"
              style="width: 100%"
              :disabled="true"
            />
          </template>
        </el-table-column>
        <el-table-column prop="taxRate" label="税率" width="100">
          <template #default="scope">
            <el-select
              v-model="scope.row.taxRate"
              placeholder="请选择税率"
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="rate in taxRates"
                :key="rate.value"
                :label="`${rate.value}%`"
                :value="rate.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="unitPriceIncludingTax" label="含税单价" width="120">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.unitPriceIncludingTax"
              :min="0"
              :precision="2"
              style="width: 100%"
              @change="calculateDetailTotal(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="amountIncludingTax" label="含税金额" width="120">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.amountIncludingTax"
              :min="0"
              :precision="2"
              style="width: 100%"
              :disabled="true"
            />
          </template>
        </el-table-column>
          <el-table-column label="操作" width="80" fixed="right">
            <template #default="scope">
              <el-button
                type="danger"
                link
                @click="removeDetailItem(scope.$index)"
              >
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="detail-summary">
          <span class="summary-item">总量: {{ totalQuantity }}</span>
          <span class="summary-item">总金额: {{ formatCurrency(totalAmount) }}</span>
        </div>
      </div>

      <!-- 附件 -->
      <div class="form-section">
        <h3 class="section-title">附件</h3>
        <div class="attachment-container">
          <div class="attachment-list" v-if="form.attachments && form.attachments.length > 0">
            <div
              v-for="attachment in form.attachments"
              :key="attachment.id"
              class="attachment-item"
            >
              <div class="attachment-info">
                <div class="file-name">{{ attachment.fileName }}</div>
                <div class="file-size">{{ formatFileSize(attachment.fileSize) }}</div>
                <div class="upload-time">{{ formatDateTime(attachment.uploadTime) }}</div>
              </div>
              <div class="attachment-actions">
                <el-button type="primary" link @click="reuploadAttachment(attachment)">
                  重新上传
                </el-button>
                <el-button type="danger" link @click="deleteAttachment(attachment)">
                  删除
                </el-button>
              </div>
            </div>
          </div>
          <div class="upload-area" v-else>
            <el-upload
              class="upload-dragger"
              drag
              action="#"
              :auto-upload="false"
              :on-change="handleFileChange"
              :show-file-list="false"
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                点击上传 / 拖拽到此区域
              </div>
            </el-upload>
          </div>
        </div>
      </div>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, nextTick, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { purchaseOrderApi } from '@/api/purchaseOrderApi'
import { referenceApi } from '@/api/referenceApi'
import type {
  PurchaseOrderDto,
  CreatePurchaseOrderCommand,
  UpdatePurchaseOrderCommand,
  CreatePurchaseOrderDetailCommand,
  UpdatePurchaseOrderDetailCommand,
  PurchaseOrderAttachment,
  ResultCode
} from '@/types/purchaseOrder'

// Props
interface Props {
  visible: boolean
  purchaseOrder?: PurchaseOrderDto | null
  isEdit: boolean
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  'update:visible': [value: boolean]
  'success': []
}>()

// 响应式数据
const formRef = ref<FormInstance>()
const submitting = ref(false)
const selectedDetails = ref<any[]>([])

// 表单数据
const form = reactive<CreatePurchaseOrderCommand>({
  orderSubject: '',
  isSystemNumber: true,
  purchaseOrderNumber: '',
  relatedSalesOrder: '',
  doNotBindSalesOrder: false,
  supplierId: 0,
  contactPhone: '',
  purchasingDepartmentId: 0,
  relatedProjectId: 0,
  deliveryAddress: '',
  remarks: '',
  relatedPurchaseRequest: '',
  doNotBindPurchaseRequest: true,
  purchaseDate: '',
  contactPerson: '',
  purchaserId: 0,
  contactMethod: '',
  settlementMethod: '现金',
  details: [],
  attachments: []
})

// 下拉框数据（从API获取）
const suppliers = ref<Array<{ id: number; name: string }>>([])
const departments = ref<Array<{ id: number; name: string }>>([])
const projects = ref<Array<{ id: number; name: string }>>([])
const persons = ref<Array<{ id: number; name: string }>>([])

// 加载状态
const loadingOptions = ref(false)

const units = ref([
  { value: '个', label: '个(主单位)' },
  { value: '包', label: '包=12个' },
  { value: '箱', label: '箱=24包' }
])

const taxRates = ref([
  { value: 0, label: '0%' },
  { value: 3, label: '3%' },
  { value: 6, label: '6%' },
  { value: 9, label: '9%' },
  { value: 13, label: '13%' }
])

const settlementMethods = ref([
  { value: '现金', label: '现金' },
  { value: '银行转账', label: '银行转账' },
  { value: '支票', label: '支票' },
  { value: '信用', label: '信用' },
  { value: '其他', label: '其他' }
])

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const hasSelectedDetails = computed(() => selectedDetails.value.length > 0)

const totalQuantity = computed(() => {
  return form.details.reduce((sum, item) => sum + (item.purchaseQuantity || 0), 0)
})

const totalAmount = computed(() => {
  return form.details.reduce((sum, item) => sum + (item.amountIncludingTax || 0), 0)
})

// 表单验证规则
const rules: FormRules = {
  orderSubject: [
    { required: true, message: '请输入订单主题', trigger: 'blur' }
  ],
  supplierId: [
    { required: true, message: '请选择供应商', trigger: 'change' }
  ],
  purchasingDepartmentId: [
    { required: true, message: '请选择采购部门', trigger: 'change' }
  ],
  purchaserId: [
    { required: true, message: '请选择采购人员', trigger: 'change' }
  ],
  purchaseDate: [
    { required: true, message: '请选择采购日期', trigger: 'change' }
  ],
  settlementMethod: [
    { required: true, message: '请选择结算方式', trigger: 'change' }
  ]
}

// 监听器
watch(() => props.purchaseOrder, (newVal) => {
  // 简化监听器，避免复杂的初始化逻辑
  console.log('purchaseOrder changed:', newVal)
}, { immediate: false })

// 加载下拉框选项数据
const loadOptions = async () => {
  try {
    loadingOptions.value = true
    console.log('开始加载下拉框选项数据...')
    
    // 并行加载所有选项数据
    const [personsRes, industriesRes, locationsRes] = await Promise.all([
      referenceApi.getAllPersons(),
      referenceApi.getAllIndustries(),
      referenceApi.getAllLocations()
    ])
    
    // 处理人员数据
    if (personsRes.code === 200 && personsRes.data) {
      const personsData = Array.isArray(personsRes.data) ? personsRes.data : []
      persons.value = personsData.map((p: any) => ({
        id: p.id ?? p.Id ?? 0,
        name: p.personName ?? p.name ?? p.Name ?? '未知人员'
      }))
      console.log('人员数据加载成功:', persons.value)
    }
    
    // 处理行业数据（作为项目数据）
    if (industriesRes.code === 200 && industriesRes.data) {
      const industriesData = Array.isArray(industriesRes.data) ? industriesRes.data : []
      projects.value = industriesData.map((i: any) => ({
        id: i.id ?? i.Id ?? 0,
        name: i.industryName ?? i.name ?? i.Name ?? '未知行业'
      }))
      console.log('项目数据加载成功:', projects.value)
    }
    
    // 处理地区数据（作为部门数据）
    if (locationsRes.code === 200 && locationsRes.data) {
      const locationsData = Array.isArray(locationsRes.data) ? locationsRes.data : []
      departments.value = locationsData.map((l: any) => ({
        id: l.id ?? l.Id ?? 0,
        name: l.locationName ?? l.name ?? l.Name ?? '未知地区'
      }))
      console.log('部门数据加载成功:', departments.value)
    }
    
    // 模拟供应商数据（实际项目中应该有专门的供应商API）
    suppliers.value = [
      { id: 1, name: '供应商A - 电子产品' },
      { id: 2, name: '供应商B - 原材料' },
      { id: 3, name: '供应商C - 机械设备' },
      { id: 4, name: '供应商D - 办公用品' },
      { id: 5, name: '供应商E - 包装材料' }
    ]
    console.log('供应商数据设置完成:', suppliers.value)
    
    console.log('所有下拉框选项数据加载完成')
  } catch (error) {
    console.error('加载下拉框选项数据失败:', error)
    ElMessage.error('加载选项数据失败，请刷新页面重试')
    
    // 设置默认数据作为兜底
    suppliers.value = [
      { id: 1, name: '默认供应商' }
    ]
    departments.value = [
      { id: 1, name: '默认部门' }
    ]
    projects.value = [
      { id: 1, name: '默认项目' }
    ]
    persons.value = [
      { id: 1, name: '默认人员' }
    ]
  } finally {
    loadingOptions.value = false
  }
}

// 生命周期钩子
onMounted(() => {
  console.log('PurchaseOrderForm mounted')
  // 加载下拉框选项数据
  loadOptions()
  // 初始化表单
  resetForm()
})

// 监听visible变化，当对话框打开时初始化表单
watch(() => props.visible, (newVal) => {
  if (newVal) {
    console.log('对话框打开，初始化表单')
    if (props.isEdit && props.purchaseOrder) {
      // 编辑模式，填充现有数据
      Object.assign(form, {
        orderSubject: props.purchaseOrder.orderSubject || '',
        isSystemNumber: props.purchaseOrder.isSystemNumber,
        purchaseOrderNumber: props.purchaseOrder.purchaseOrderNumber || '',
        relatedSalesOrder: props.purchaseOrder.relatedSalesOrder || '',
        doNotBindSalesOrder: props.purchaseOrder.doNotBindSalesOrder,
        supplierId: props.purchaseOrder.supplierId || 0,
        contactPhone: props.purchaseOrder.contactPhone || '',
        purchasingDepartmentId: props.purchaseOrder.purchasingDepartmentId || 0,
        relatedProjectId: props.purchaseOrder.relatedProjectId || 0,
        deliveryAddress: props.purchaseOrder.deliveryAddress || '',
        remarks: props.purchaseOrder.remarks || '',
        relatedPurchaseRequest: props.purchaseOrder.relatedPurchaseRequest || '',
        doNotBindPurchaseRequest: props.purchaseOrder.doNotBindPurchaseRequest,
        purchaseDate: props.purchaseOrder.purchaseDate || '',
        contactPerson: props.purchaseOrder.contactPerson || '',
        purchaserId: props.purchaseOrder.purchaserId || 0,
        contactMethod: props.purchaseOrder.contactMethod || '',
        settlementMethod: props.purchaseOrder.settlementMethod || '现金',
        details: props.purchaseOrder.details || [],
        attachments: props.purchaseOrder.attachments || []
      })
    } else {
      // 新增模式，重置表单
      resetForm()
    }
  }
}, { immediate: true })

// 方法
const resetForm = () => {
  // 生成新的采购单号
  const now = new Date()
  const timestamp = now.getTime()
  const random = Math.floor(Math.random() * 10000)
  const newOrderNumber = `CGDH${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}${random}`
  
  Object.assign(form, {
    orderSubject: '',
    isSystemNumber: true,
    purchaseOrderNumber: newOrderNumber,
    relatedSalesOrder: '',
    doNotBindSalesOrder: false,
    supplierId: 0,
    contactPhone: '',
    purchasingDepartmentId: 0,
    relatedProjectId: 0,
    deliveryAddress: '',
    remarks: '',
    relatedPurchaseRequest: '',
    doNotBindPurchaseRequest: true,
    purchaseDate: now.toISOString().split('T')[0], // 设置当前日期
    contactPerson: '',
    purchaserId: 0,
    contactMethod: '',
    settlementMethod: '现金',
    details: []
  })
  
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const addDetailItem = () => {
  const newItem: CreatePurchaseOrderDetailCommand = {
    serialNumber: form.details.length + 1,
    itemNumber: `WPBH${Date.now()}${Math.floor(Math.random() * 1000000)}`,
    itemName: '旺能胶水250',
    specificationModel: 'WH-002',
    unit: '个',
    brand: '降龙十八掌',
    purchaseQuantity: 0,
    mainUnitQuantity: 0,
    taxRate: 0,
    unitPriceIncludingTax: 0,
    unitPriceExcludingTax: 0,
    amountIncludingTax: 0,
    amountExcludingTax: 0
  }
  form.details.push(newItem)
  console.log('添加明细项:', newItem)
  console.log('当前明细列表:', form.details)
}

const removeDetailItem = (index: number) => {
  form.details.splice(index, 1)
  // 重新计算序号
  form.details.forEach((item, idx) => {
    item.serialNumber = idx + 1
  })
}

const removeDetailItems = () => {
  const indices = selectedDetails.value.map(item => form.details.indexOf(item))
  indices.sort((a, b) => b - a).forEach(index => {
    form.details.splice(index, 1)
  })
  // 重新计算序号
  form.details.forEach((item, idx) => {
    item.serialNumber = idx + 1
  })
  selectedDetails.value = []
}

const handleDetailSelectionChange = (rows: any[]) => {
  selectedDetails.value = rows
}

const calculateDetailTotal = (item: any) => {
  if (item.purchaseQuantity && item.unitPriceIncludingTax) {
    item.amountIncludingTax = item.purchaseQuantity * item.unitPriceIncludingTax
    item.amountExcludingTax = item.amountIncludingTax / (1 + item.taxRate / 100)
    item.unitPriceExcludingTax = item.unitPriceIncludingTax / (1 + item.taxRate / 100)
    item.mainUnitQuantity = item.purchaseQuantity
  } else {
    item.amountIncludingTax = 0
    item.amountExcludingTax = 0
    item.unitPriceExcludingTax = 0
    item.mainUnitQuantity = 0
  }
}

const handleFileChange = (file: any) => {
  // 处理文件上传
  const attachment: PurchaseOrderAttachment = {
    id: Date.now(),
    purchaseOrderId: 0,
    fileName: file.name,
    fileSize: file.size,
    filePath: '',
    uploadTime: new Date().toISOString(),
    uploadBy: ''
  }
  
  if (!form.attachments) {
    form.attachments = []
  }
  form.attachments.push(attachment)
  
  ElMessage.success('文件上传成功')
}

const reuploadAttachment = (attachment: PurchaseOrderAttachment) => {
  // 重新上传附件
  ElMessage.info('重新上传功能开发中...')
}

const deleteAttachment = (attachment: PurchaseOrderAttachment) => {
  if (form.attachments) {
    const index = form.attachments.findIndex(a => a.id === attachment.id)
    if (index > -1) {
      form.attachments.splice(index, 1)
      ElMessage.success('附件删除成功')
    }
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    
    if (form.details.length === 0) {
      ElMessage.warning('请至少添加一个物品明细')
      return
    }

    // 逐条校验明细必填与范围
    for (const [idx, d] of form.details.entries()) {
      if (!d.itemNumber || !d.itemName) {
        ElMessage.error(`第${idx + 1}行明细：物品编号和名称不能为空`)
        return
      }
      if (!d.purchaseQuantity || d.purchaseQuantity <= 0) {
        ElMessage.error(`第${idx + 1}行明细：采购数量必须大于0`)
        return
      }
      if (!d.unitPriceIncludingTax && d.unitPriceIncludingTax !== 0) {
        ElMessage.error(`第${idx + 1}行明细：请填写含税单价`)
        return
      }
      // 与后端规则一致：主单位数量必须>0
      d.mainUnitQuantity = d.purchaseQuantity
      if (!d.mainUnitQuantity || d.mainUnitQuantity <= 0) {
        ElMessage.error(`第${idx + 1}行明细：主单位数量必须大于0`)
        return
      }
      // 默认填充不含税单价，避免Required失败
      if (d.unitPriceExcludingTax === undefined || d.unitPriceExcludingTax === null) {
        d.unitPriceExcludingTax = Number(d.unitPriceIncludingTax) / (1 + Number(d.taxRate || 0) / 100)
      }
      // 金额联动
      calculateDetailTotal(d)
    }

    submitting.value = true

    if (props.isEdit) {
      // 更新模式
      const updateCommand: UpdatePurchaseOrderCommand = {
        id: props.purchaseOrder!.id,
        ...form,
        details: form.details.map(detail => ({
          ...detail,
          purchaseOrderId: props.purchaseOrder!.id
        }))
      }
      
      const response = await purchaseOrderApi.updatePurchaseOrder(updateCommand)
      if (response.code === 200) {
        ElMessage.success('更新成功')
        emit('success')
      } else {
        ElMessage.error(response.message || '更新失败')
      }
    } else {
      // 新增模式
      const createCommand: CreatePurchaseOrderCommand = {
        orderSubject: form.orderSubject.trim(),
        isSystemNumber: form.isSystemNumber,
        // 后端在系统编号时会忽略该字段，这里仅在非系统编号时传递
        purchaseOrderNumber: form.isSystemNumber ? undefined : form.purchaseOrderNumber?.trim(),
        relatedSalesOrder: form.relatedSalesOrder?.trim() || undefined,
        doNotBindSalesOrder: !!form.doNotBindSalesOrder,
        supplierId: Number(form.supplierId) || 0,
        contactPhone: form.contactPhone?.trim() || undefined,
        purchasingDepartmentId: form.purchasingDepartmentId ? Number(form.purchasingDepartmentId) : undefined,
        relatedProjectId: form.relatedProjectId ? Number(form.relatedProjectId) : undefined,
        deliveryAddress: form.deliveryAddress?.trim() || undefined,
        remarks: form.remarks?.trim() || undefined,
        relatedPurchaseRequest: form.relatedPurchaseRequest?.trim() || undefined,
        doNotBindPurchaseRequest: !!form.doNotBindPurchaseRequest,
        // 转换为 yyyy-MM-dd 的日期字符串，后端能解析为DateTime
        purchaseDate: typeof form.purchaseDate === 'string' ? form.purchaseDate : new Date(form.purchaseDate).toISOString().split('T')[0],
        contactPerson: form.contactPerson?.trim() || undefined,
        purchaserId: form.purchaserId ? Number(form.purchaserId) : undefined,
        contactMethod: form.contactMethod?.trim() || undefined,
        settlementMethod: form.settlementMethod,
        details: form.details.map(d => ({
          serialNumber: Number(d.serialNumber) || 0,
          itemNumber: (d.itemNumber || '').trim(),
          itemName: (d.itemName || '').trim(),
          specificationModel: d.specificationModel?.trim() || undefined,
          unit: d.unit?.trim() || undefined,
          brand: d.brand?.trim() || undefined,
          purchaseQuantity: Number(d.purchaseQuantity) || 0,
          mainUnitQuantity: Number(d.mainUnitQuantity) || 0,
          taxRate: Number(d.taxRate) || 0,
          unitPriceIncludingTax: Number(d.unitPriceIncludingTax) || 0,
          unitPriceExcludingTax: Number(d.unitPriceExcludingTax) || 0,
          amountIncludingTax: Number(d.amountIncludingTax) || 0,
          amountExcludingTax: Number(d.amountExcludingTax) || 0
        })),
        attachments: form.attachments && form.attachments.length > 0 ? form.attachments : undefined
      }

      // 额外的前置校验，避免400
      if (!createCommand.supplierId || createCommand.supplierId < 1) {
        ElMessage.error('请选择供应商')
        submitting.value = false
        return
      }
      if (!createCommand.purchasingDepartmentId) {
        ElMessage.error('请选择采购部门')
        submitting.value = false
        return
      }
      if (!createCommand.purchaserId) {
        ElMessage.error('请选择采购人员')
        submitting.value = false
        return
      }

      const response = await purchaseOrderApi.createPurchaseOrder(createCommand)
      if (response.code === 200) {
        ElMessage.success('创建成功')
        emit('success')
      } else {
        ElMessage.error(response.message || '创建失败')
      }
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败，请检查表单')
  } finally {
    submitting.value = false
  }
}

const handleCancel = () => {
  dialogVisible.value = false
  resetForm()
}

// 工具方法
const formatCurrency = (amount: number) => {
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY'
  }).format(amount || 0)
}

const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
</script>

<style scoped>
.purchase-order-form {
  max-height: 70vh;
  overflow-y: auto;
}

.form-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background: #fafafa;
}

.section-title {
  margin: 0 0 20px 0;
  padding-bottom: 10px;
  border-bottom: 2px solid #409eff;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.detail-actions {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
}

.detail-summary {
  margin-top: 15px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
  display: flex;
  gap: 30px;
}

.summary-item {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.attachment-container {
  display: flex;
  gap: 20px;
}

.attachment-list {
  flex: 1;
}

.attachment-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  margin-bottom: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background: white;
}

.attachment-info {
  flex: 1;
}

.file-name {
  font-weight: 600;
  color: #303133;
  margin-bottom: 5px;
}

.file-size,
.upload-time {
  font-size: 12px;
  color: #909399;
}

.attachment-actions {
  display: flex;
  gap: 10px;
}

.upload-area {
  flex: 1;
}

.upload-dragger {
  width: 100%;
  height: 200px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 